<template>
    <div class="login-container">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
            <div class="title-container">
                <h3 class="title">智能机器人平台</h3>
            </div>
            <el-form-item prop="account">
                <el-input ref="account" v-model="loginForm.account" placeholder="请输入您的账号（账号、手机号或邮箱）">
                    <span slot="prefix" class="iconfont icon-zhanghao"></span>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="请输入密码"
                          @keyup.enter.native="handleLogin">
                    <span slot="prefix" class="iconfont icon-mima"></span>
                    <span slot="suffix" :class="['iconfont', passwordType == 'password' ? 'icon-yanjing' : 'icon-yanjingguanbi']"
                          @click="showPwd"></span>
                </el-input>
            </el-form-item>
            <el-form-item prop="graphCaptcha" class="graphCaptcha">
                <el-input ref="graphCaptcha" v-model="loginForm.graphCaptcha" placeholder="请输入验证码">
                    <span slot="prefix" class="iconfont icon-yanzhengma"></span>
                </el-input>
                <img :src="graphCaptchaData.base64GraphCaptcha" @click="getGraphCaptcha" />
            </el-form-item>
            <el-button type="primary" class="loginButton" @click.native.prevent="handleLogin" :disabled="isDisabled">登录</el-button>
            <div class="flexbetween">
                <p class="tips">
                    还没有账号？<router-link :to="{name:'register'}">去注册</router-link>
                </p>
                <router-link :to="{name:'reset'}">忘记密码</router-link>
            </div>
        </el-form>
    </div>
</template>

<script>
import { getGraphCaptcha, verifyGraphCaptcha, getLoginUserInfo } from "@/api/login";
export default {
    name: "Login",
    data() {
        var validateGraphCaptcha = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入图形验证码'));
            } else {
                var param = {
                    graphCaptcha: this.loginForm.graphCaptcha,
                    graphCaptchaId: this.graphCaptchaData.id
                }
                if (!this.isDisabled) {
                    verifyGraphCaptcha(param).then(resp => {
                        if (resp.status == 0) {
                            callback();
                        } else {
                            callback(new Error(resp.message));
                        }
                    });
                } else {
                    callback();
                }
            }
        };
        return {
            graphCaptchaData: {},
            loginForm: {
                account: "",
                password: "",
                graphCaptcha: ""
            },
            loginRules: {
                account: [{ required: true, trigger: "blur", message: "请输入您的账号（账号、手机号或邮箱）" }],
                password: [{ required: true, trigger: "blur", message: "请输入密码" }],
                graphCaptcha: [{ required: true, validator: validateGraphCaptcha, trigger: 'blur' }],
            },
            loading: false,
            passwordType: "password",
            redirect: undefined,
            isDisabled: false,
        };
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect;
            },
            immediate: true,
        },
    },
    methods: {
        getGraphCaptcha() {
            getGraphCaptcha().then(resp => {
                if (resp.status == 0) {
                    this.graphCaptchaData = resp.data;
                }
            });
        },
        showPwd() {
            if (this.passwordType === "password") {
                this.passwordType = "";
            } else {
                this.passwordType = "password";
            }
            this.$nextTick(() => {
                this.$refs.password.focus();
            });
        },
        handleLogin(isKeyDown = false) {
            if (isKeyDown) {
                this.$refs.graphCaptcha.blur();
            }
            if (!this.isDisabled) {
                this.isDisabled = true;
                this.$refs.loginForm.validate((valid) => {
                    if (valid) {
                        let loading = this.$loading({
                            lock: true,
                            text: "登录中",
                            spinner: "el-icon-loading",
                            background: "rgba(0, 0, 0, 0.7)",
                        });
                        var param = Object.assign({}, this.loginForm, { graphCaptchaId: this.graphCaptchaData.id });
                        this.$store.dispatch("user/login", param).then(() => {
                            this.isDisabled = false;
                            getLoginUserInfo().then(resp => {
                                if (resp.status == 0) {
                                    this.$store.dispatch("user/setUserInfo", resp.data).then(() => {
                                        this.$router.push({ path: this.redirect || "/" });
                                        loading.close();
                                    });
                                } else {
                                    this.$antMessage.warning(resp.message);
                                }
                            });
                        }).catch((resp) => {
                            loading.close();
                            this.isDisabled = false;
                            this.$antMessage.warning(resp.message);
                        });
                    } else {
                        this.isDisabled = false;
                    }
                });
            }
        },
        keyDown(e) {
            if (e.keyCode === 13) {
                this.handleLogin(true);
            }
        },
    },
    created() {
        this.getGraphCaptcha();
    },
    mounted() {
        window.addEventListener('keydown', this.keyDown);
    },
    destroyed() {
        window.removeEventListener('keydown', this.keyDown, false);
    }
};
</script>

<style lang="scss">
.login-container {
    display: flex;
    min-height: 100%;
    width: 100%;
    overflow: hidden;
    background-color: #f3f6ff;
    background-image: url("../../assets/images/loginBg.png");
    background-size: 100% 100%;
    .login-form {
        margin: auto;
        position: relative;
        width: 560px;
        height: 490px;
        padding: 60px 80px 0;
        border-radius: 20px;
        background: #fff;
        box-shadow: 0px 0px 30px 0px rgba(12, 8, 47, 0.15);
        .el-form-item {
            margin-bottom: 30px;
            .el-input__inner {
                border-radius: 6px;
            }
        }
        .el-form-item__error {
            padding-top: 8px;
        }
        .graphCaptcha {
            .el-form-item__content {
                display: flex;
                img {
                    cursor: pointer;
                    width: 120px;
                    height: 40px;
                    margin-left: 20px;
                    flex-shrink: 0;
                    border-radius: 6px;
                    border: 1px solid #6b5ee2;
                }
            }
        }
        .el-input__inner {
            padding-left: 38px;
        }
        .el-input--suffix {
            .el-input__inner {
                padding-right: 38px;
            }
        }
        .el-input__prefix {
            left: 0;
            width: 38px;
        }
        .el-input__suffix {
            right: 0;
            width: 38px;
        }
        .iconfont {
            color: #b7c1c9 !important;
        }
    }
    .loginButton {
        width: 100%;
        margin-bottom: 20px;
    }
    .title-container {
        position: relative;
        .title {
            color: #363c43;
            font-size: 26px;
            margin-bottom: 40px;
            text-align: center;
            font-weight: bold;
        }
    }
    .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        font-size: 16px;
        color: #90979d;
        cursor: pointer;
        user-select: none;
    }
    .tips {
        color: #90979d;
        a,
        & + a {
            color: #6b5ee2;
        }
    }
}
</style>
